#include "AHT21.h"
#include "string.h"
void AHT21_Init(void)
{
    uint8_t read_buffer;
    HAL_Delay(100); // 等待传感器上电稳定
    HAL_I2C_Master_Receive(&hi2c2, AHT21_ADDRESS << 1, &read_buffer, 1, HAL_MAX_DELAY);
    if((read_buffer & 0x18) != 0x18) // 检查传感器状态
    {
        uint8_t init_cmd[3] = {0xE1, 0x08, 0x00}; // 初始化命令
        HAL_I2C_Master_Transmit(&hi2c2, AHT21_ADDRESS << 1, init_cmd, 3, HAL_MAX_DELAY);
        HAL_Delay(10); // 等待初始化完成
    }
}

void AHT21_Read(float *temperature, float *humidity)
{
    HAL_Delay(10);
    uint8_t cmd[3] = {0xAC, 0x33, 0x00}; // 触发测量命令
    HAL_I2C_Master_Transmit(&hi2c2, AHT21_ADDRESS, cmd, 3, HAL_MAX_DELAY);
    HAL_Delay(80); // 等待测量完成

    uint8_t data[6];
    HAL_I2C_Master_Receive(&hi2c2, AHT21_ADDRESS, data, 6, HAL_MAX_DELAY);
    if((data[0] & 0x80) == 0) // 检查数据是否有效
    {
        uint32_t raw_humidity = (((uint32_t)(data[1] << 12)) | ((uint32_t)(data[2] << 4)) | ((data[3] >> 4) & 0x0F));
        uint32_t raw_temperature = (((uint32_t)((data[3] & 0x0F) << 16)) | ((uint32_t)(data[4] << 8)) | data[5]);
        *humidity = (raw_humidity * 100.0f) / 1048576.0f; // 转换为百分比
        *temperature = (raw_temperature * 200.0f / 1048576.0f) - 50.0f; // 转换为摄氏度
    }
    else
    {
        *humidity = -1; // 无效数据标志
        *temperature = -100; // 无效数据标志
    }
}
